<template>
  <div class="personal-info">
    <!-- 头部 -->
    <div class="header">
      <i class="fas fa-arrow-left" @click="goBack"></i>
      <h3>个人信息</h3>
      <div class="header-placeholder"></div>
    </div>

    <!-- 表单内容 -->
    <div class="content">
      <div class="form-section">
        <!-- 头像 -->
        <div class="form-item avatar-item" @click="changeAvatar">
          <label>头像</label>
          <div class="avatar-right">
            <img :src="formData.photo || require('@/assets/userImg/userImg.png')" alt="头像" class="avatar-img">
            <i class="fas fa-chevron-right"></i>
          </div>
        </div>

        <!-- 用户名（只读） -->
        <div class="form-item">
          <label>用户名</label>
          <input type="text" v-model="formData.username" placeholder="用户名" disabled>
        </div>

        <!-- 姓 -->
        <div class="form-item">
          <label>姓</label>
          <input type="text" v-model="formData.lastName" placeholder="请输入姓">
        </div>

        <!-- 名 -->
        <div class="form-item">
          <label>名</label>
          <input type="text" v-model="formData.firstName" placeholder="请输入名">
        </div>

        <!-- 手机号 -->
        <div class="form-item">
          <label>手机号</label>
          <input type="tel" v-model="formData.phone" placeholder="请输入手机号">
        </div>

        <!-- 邮箱 -->
        <div class="form-item">
          <label>邮箱</label>
          <input type="email" v-model="formData.email" placeholder="请输入邮箱">
        </div>

        <!-- 性别 -->
        <div class="form-item">
          <label>性别</label>
          <div class="gender-options">
            <label class="gender-option">
              <input type="radio" v-model="formData.gender" value="男">
              <span class="radio-custom"></span>
              <span>男</span>
            </label>
            <label class="gender-option">
              <input type="radio" v-model="formData.gender" value="女">
              <span class="radio-custom"></span>
              <span>女</span>
            </label>
          </div>
        </div>
      </div>

      <button class="save-btn" @click="saveInfo" :disabled="saving">
        {{ saving ? '保存中...' : '保存' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { userAPI } from '@/api/user.js'

const router = useRouter()
const saving = ref(false)

const formData = ref({
  username: '',
  firstName: '',
  lastName: '',
  phone: '',
  email: '',
  gender: '',
  photo: ''
})


// 用户信息
const userInfo = ref({
  firstName: '',
  lastName: '',
  phone: '',
  email: '',
  username: '',
  photo: ''
})

onMounted(async () => {
  await loadUserInfo()
})

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const response = await userAPI.information()
    console.log('完整响应:', response)

    // 简化数据处理逻辑
    let data = null

    // 根据实际响应结构调整
    if (response.data && response.data.success === true && response.data.data) {
      // 如果后端返回 { success: true, code: 'OK', data: {...}, message: null }
      data = response.data.data
    } else if (response.data && response.data.id) {
      // 如果后端直接返回 Person 对象
      data = response.data
    } else {
      // 其他情况
      data = response.data
    }

    console.log('提取的用户数据:', data)

    if (data) {
      userInfo.value = data
      formData.value = {
        username: data.username || '',
        firstName: data.firstName || '',
        lastName: data.lastName || '',
        phone: data.phone || '',
        email: data.email || '',
        gender: data.gender || '',
        photo: data.photo || ''
      }
    } else {
      console.error('未获取到用户数据')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 更换头像（简化版）
const changeAvatar = () => {
  // 实际项目中这里应该调用相册或拍照
  alert('头像更换功能开发中...')
}

// 保存信息
const saveInfo = async () => {
  // 基本验证
  if (!formData.value.phone.trim()) {
    alert('请输入手机号')
    return
  }

  if (formData.value.phone && !/^1[3-9]\d{9}$/.test(formData.value.phone)) {
    alert('请输入正确的手机号码')
    return
  }

  if (formData.value.email && !/\S+@\S+\.\S+/.test(formData.value.email)) {
    alert('请输入正确的邮箱地址')
    return
  }

  saving.value = true
  try {
    // 只发送需要更新的字段
    const updateData = {
      firstName: formData.value.firstName,
      lastName: formData.value.lastName,
      phone: formData.value.phone,
      email: formData.value.email,
      gender: formData.value.gender
      // photo 字段暂时不处理
    }

    console.log('发送更新数据:', updateData)

    const response = await userAPI.updateInformation(updateData)
    console.log('更新响应:', response)

    alert('保存成功')
    router.push('/userProfile')
  } catch (error) {
    console.error('保存失败:', error)
    const errorMessage = error.response?.data?.message || '保存失败，请稍后重试'
    alert('保存失败：' + errorMessage)
  } finally {
    saving.value = false
  }
}
</script>

<style scoped>
.personal-info {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4vw;
  background: white;
  border-bottom: 1px solid #eee;
}

.header i {
  font-size: 5vw;
  color: #666;
  cursor: pointer;
}

.header h3 {
  font-size: 4.5vw;
  font-weight: normal;
  color: #333;
}

.header-placeholder {
  width: 5vw;
}

.content {
  padding: 4vw;
}

.form-section {
  background: white;
  border-radius: 2vw;
  overflow: hidden;
  margin-bottom: 4vw;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 4vw;
  border-bottom: 1px solid #f0f0f0;
  font-size: 4vw;
}

.form-item:last-child {
  border-bottom: none;
}

.form-item label {
  width: 20vw;
  color: #333;
  font-weight: 500;
}

.form-item input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 4vw;
  color: #333;
  background: transparent;
}

.form-item input:disabled {
  color: #999;
  background: transparent;
}

.form-item input::placeholder {
  color: #ccc;
}

.avatar-item {
  cursor: pointer;
}

.avatar-right {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.avatar-img {
  width: 10vw;
  height: 10vw;
  border-radius: 50%;
  margin-right: 2vw;
  object-fit: cover;
}

.gender-options {
  flex: 1;
  display: flex;
  gap: 4vw;
}

.gender-option {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.gender-option input[type="radio"] {
  display: none;
}

.radio-custom {
  width: 4vw;
  height: 4vw;
  border: 2px solid #ddd;
  border-radius: 50%;
  margin-right: 2vw;
  position: relative;
  transition: all 0.3s;
}

.gender-option input[type="radio"]:checked + .radio-custom {
  border-color: #ee5a24;
  background-color: #ee5a24;
}

.gender-option input[type="radio"]:checked + .radio-custom::after {
  content: '';
  width: 2vw;
  height: 2vw;
  background: white;
  border-radius: 50%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.save-btn {
  width: 100%;
  padding: 4vw;
  background: linear-gradient(135deg, #ff6b6b, #ee5a24);
  color: white;
  border: none;
  border-radius: 2vw;
  font-size: 4.5vw;
  cursor: pointer;
  transition: opacity 0.3s;
}

.save-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.save-btn:active {
  opacity: 0.8;
}
</style>